<script lang="ts" setup>
import {
  IconAddCircle,
  IconRefreshLine,
  VButton,
  VCard,
  VPageHeader,
  VPagination,
  VSpace,
  VTag,
  VEntity,
  VEntityField,
  VStatusDot,
  VDropdownItem,
  VLoading,
  VEmpty,
  Dialog,
  Toast,
} from "@halo-dev/components";
import SearchInput from "@console/components/input/SearchInput.vue";
import { computed, ref, watch } from "vue";
import type { ProductType } from "@console/types";
import { productTypeApiClient } from "@console/api/product";
import { formatDatetime } from "@console/utils/date";
import ProductTypeEditingModal from "./ProductTypeEditingModal.vue";
import { useQuery } from "@tanstack/vue-query";

const page = ref(1);
const size = ref(20);
const keyword = ref("");
const editingModal = ref(false);
const selectedProductType = ref<ProductType>();

const total = ref(0);

const {
  data: productTypes,
  isLoading: loading,
  isFetching,
  refetch,
} = useQuery<ProductType[]>({
  queryKey: ["product-types", page, size, keyword],
  queryFn: async () => {
    const { data } = await productTypeApiClient.listProductTypes({
      page: page.value,
      size: size.value,
      keyword: keyword.value,
    });

    total.value = data.total;
    return data.items;
  },
  refetchInterval(data) {
    // 检查是否有正在删除的产品类型
    const hasDeletingData = data?.some(
      (productType) => !!productType.metadata?.deletionTimestamp
    );
    return hasDeletingData ? 1000 : false;
  },
});

const handleOpenEditingModal = (productType?: ProductType) => {
  selectedProductType.value = productType;
  editingModal.value = true;
};

const onEditingModalClose = () => {
  selectedProductType.value = undefined;
  editingModal.value = false;
  refetch();
};

const handleDelete = async (productType: ProductType) => {
  Dialog.warning({
    title: "确定要删除该产品类型吗？",
    description: "删除之后将无法恢复",
    confirmType: "danger",
    onConfirm: async () => {
      try {
        await productTypeApiClient.deleteProductType({
          name: productType.metadata?.name,
        });

        Toast.success("删除成功");
        await refetch();
      } catch (error) {
        console.error("Failed to delete product type", error);
      }
    },
  });
};

const handlePaginationChange = ({
  page: newPage,
  size: newSize,
}: {
  page: number;
  size: number;
}) => {
  page.value = newPage;
  size.value = newSize;
};

watch([() => keyword.value], () => {
  page.value = 1;
});
</script>

<template>
  <div>
    <VPageHeader title="产品类型">
      <template #icon>
        <IconAddCircle class="mr-2 self-center" />
      </template>
    <template #actions>
      <VSpace>
        <VButton
          v-permission="['system:product-types:manage']"
          type="secondary"
          @click="refetch"
        >
          <template #icon>
            <IconRefreshLine class="h-4 w-4" />
          </template>
          刷新
        </VButton>
        <VButton
          v-permission="['system:product-types:manage']"
          type="primary"
          @click="handleOpenEditingModal()"
        >
          <template #icon>
            <IconAddCircle class="h-4 w-4" />
          </template>
          新建
        </VButton>
      </VSpace>
    </template>
    </VPageHeader>

    <div class="m-0 md:m-4">
      <VCard :body-class="['!p-0']">
      <template #header>
        <div class="block w-full bg-gray-50 px-4 py-3">
          <div class="relative flex flex-col items-start sm:flex-row sm:items-center">
            <div class="flex w-full flex-1 sm:w-auto">
              <SearchInput
                v-model="keyword"
                placeholder="输入关键词搜索"
              />
            </div>
          </div>
        </div>
      </template>

      <VLoading v-if="loading" />
      <Transition v-else-if="!productTypes?.length" appear name="fade">
        <VEmpty
          message="你可以尝试刷新或者新建产品类型"
          title="当前没有产品类型"
        >
          <template #actions>
            <VSpace>
              <VButton @click="refetch">刷新</VButton>
              <VButton
                v-permission="['system:product-types:manage']"
                type="primary"
                @click="handleOpenEditingModal()"
              >
                <template #icon>
                  <IconAddCircle class="h-4 w-4" />
                </template>
                新建产品类型
              </VButton>
            </VSpace>
          </template>
        </VEmpty>
      </Transition>
      <Transition v-else appear name="fade">
        <div>
          <div class="px-4 pt-4 pb-2">
            <div class="flex items-center justify-between">
              <div class="flex items-center gap-2">
                <span class="text-sm font-medium text-gray-700">
                  共 {{ total }} 项
                </span>
              </div>
            </div>
          </div>
          <div class="overflow-hidden">
            <div class="divide-y divide-gray-100">
              <VEntity
                v-for="(productType, index) in productTypes || []"
                :key="index"
                :is-selected="false"
              >
                <template #start>
                  <div class="flex gap-3">
                    <!-- 图片预览 -->
                    <div v-if="productType.spec?.images?.length" class="flex-shrink-0">
                      <img
                        :src="productType.spec?.images?.[0]"
                        :alt="productType.spec?.displayName"
                        class="h-16 w-16 rounded-md object-cover"
                        @error="($event.target as HTMLImageElement).style.display = 'none'"
                      />
                    </div>
                    <div v-else class="flex-shrink-0">
                      <div class="h-16 w-16 rounded-md bg-gray-100 flex items-center justify-center">
                        <span class="text-gray-400 text-xs">无图片</span>
                      </div>
                    </div>
                    
                    <VEntityField
                      :title="productType.spec?.displayName"
                      :description="productType.spec?.description"
                    >
                      <template #extra>
                        <VSpace>
                          <VTag>
                            优先级: {{ productType.spec?.priority || 0 }}
                          </VTag>
                          <VTag v-if="productType.status?.productCount">
                            产品数: {{ productType.status?.productCount }}
                          </VTag>
                          <VTag v-if="productType.spec?.images?.length">
                            图片: {{ productType.spec?.images?.length }}
                          </VTag>
                        </VSpace>
                      </template>
                    </VEntityField>
                  </div>
                </template>
                <template #end>
                  <VEntityField>
                    <template #description>
                      <div class="flex flex-col items-end gap-1">
                        <span class="text-xs text-gray-500">
                          {{ formatDatetime(productType.metadata?.creationTimestamp) }}
                        </span>
                      </div>
                    </template>
                  </VEntityField>
                </template>
                <template #dropdownItems>
                  <VDropdownItem
                    v-permission="['system:product-types:manage']"
                    @click="handleOpenEditingModal(productType)"
                  >
                    修改
                  </VDropdownItem>
                  <VDropdownItem
                    v-permission="['system:product-types:manage']"
                    type="danger"
                    @click="handleDelete(productType)"
                  >
                    删除
                  </VDropdownItem>
                </template>
              </VEntity>
            </div>
          </div>
          <div class="bg-white px-4 py-4">
            <VPagination
              :page="page"
              :size="size"
              :page-label="'页'"
              :size-label="'条 / 页'"
              :total="total"
              :size-options="[20, 30, 50, 100]"
              @change="handlePaginationChange"
            />
          </div>
        </div>
      </Transition>
      </VCard>
    </div>

    <ProductTypeEditingModal
      :visible="editingModal"
      :product-type="selectedProductType"
      @update:visible="editingModal = $event"
      @close="onEditingModalClose"
    />
  </div>
</template>